import { API_URL } from '@/env';
import { router } from '@/shopro/router';
export default {
  /**
   * 跳转再封装,主要是为了兼容外链。
   * @param {String} path - 跳转路径
   * @param {isTabbar} isTabbar - 是否是底部导航
   */
  routerTo(path, isTabbar) {
    if (path) {
      // 是否跳转外部链接
      if (~path.indexOf('http') || ~path.indexOf('www')) {
        // #ifdef H5
        window.location = path;
        // #endif
        // #ifndef  H5
        router.push({
          path: '/pages/public/webview',
          query: {
            webviewPath: path,
          },
        });
        // #endif
        return false;
      }
      if (isTabbar) {
        router.replaceAll(path);
      } else {
        path.includes('/pages/index') && !path.includes('/pages/index/view')
          ? router.replaceAll(path)
          : router.push(path);
      }
    } else {
      console.log(`%cerr:没有填写跳转路径`, 'color:green;background:yellow');
    }
  },
  /**
   * 图片处理-预览图片
   * @param {Array} urls - 图片列表
   * @param {Number} current - 首个预览下标
   */
  previewImage(urls = [], current = 0) {
    uni.previewImage({
      urls: urls,
      current: current,
      indicator: 'default',
      loop: true,
      fail(err) {
        console.log('previewImage出错', urls, err);
      },
    });
  },

  /**
   * 数据分组
   * @param {Array} oArr - 原数组列表
   * @param {Number} length - 单个数组长度
   * @return {Array}  arr - 分组后的新数组
   */
  splitData(oArr = [], length = 1) {
    let arr = [];
    let minArr = [];
    oArr.forEach((c) => {
      if (minArr.length === length) {
        minArr = [];
      }
      if (minArr.length === 0) {
        arr.push(minArr);
      }
      minArr.push(c);
    });

    return arr;
  },

  /**
   * 剩余时间格式化
   * @param {Number} t - 剩余多少秒
   * @return {Object}  format - 格式后的天时分秒对象
   */
  format(t) {
    let format = {
      d: '00',
      h: '00',
      m: '00',
      s: '00',
    };
    if (t > 0) {
      let d = Math.floor(t / 86400);
      let h = Math.floor((t / 3600) % 24);
      let m = Math.floor((t / 60) % 60);
      let s = Math.floor(t % 60);
      format.d = d < 10 ? '0' + d : d;
      format.h = h < 10 ? '0' + h : h;
      format.m = m < 10 ? '0' + m : m;
      format.s = s < 10 ? '0' + s : s;
    }
    return format;
  },

  /**
   * 打电话
   * @param {String<Number>} phoneNumber - 数字字符串
   */
  callPhone(phoneNumber = '') {
    let num = phoneNumber.toString();
    uni.makePhoneCall({
      phoneNumber: num,
      fail(err) {
        console.log('makePhoneCall出错', err);
      },
    });
  },

  /**
   * 微信头像
   * @param {String} url -图片地址
   */
  checkMPUrl(url) {
    // #ifdef MP
    if (
      url.substring(0, 4) === 'http' &&
      url.substring(0, 5) !== 'https' &&
      url.substring(0, 12) !== 'http://store' &&
      url.substring(0, 10) !== 'http://tmp' &&
      url.substring(0, 10) !== 'http://usr'
    ) {
      url = 'https' + url.substring(4, url.length);
    }
    // #endif
    return url;
  },
  /**
   *  防抖
   * @param {Object} fn
   * @param {Number} delay
   * 调用 let XXX = delayDither((argv)=>{}, 600)
   * XXX()
   */
  delayDither(delay = 600) {
    let timer = null;
    return function (fn, open = true) {
      if (timer) {
        clearTimeout(timer);
      }
      const _that = this;
      let argv = arguments;
      if (open) {
        uni.showLoading({
          title: '请稍等',
          mask: true,
        });
      }
      timer = setTimeout(function () {
        if (open) {
          uni.hideLoading();
        }
        fn.apply(_that, argv);
      }, delay);
    };
  },
  base64src(base64data, fun) {
    const base64 = base64data; //base64格式图片
    const time = new Date().getTime();
    const imgPath =
      uni.env.USER_DATA_PATH + '/poster' + time + 'share' + '.mp4';
    //如果图片字符串不含要清空的前缀,可以不执行下行代码.
    // const imageData = base64.replace(/^data:video\/mp4\/\w+;base64,/, '');
    const file = uni.getFileSystemManager();
    file.writeFileSync(imgPath, base64, 'base64');
    fun(imgPath);
  },
  base64ToPath(base64) {
    return new Promise(function (resolve, reject) {
      if (typeof window === 'object' && 'document' in window) {
        base64 = base64.split(',');
        var type = base64[0].match(/:(.*?);/)[1];
        var str = atob(base64[1]);
        var n = str.length;
        var array = new Uint8Array(n);
        while (n--) {
          array[n] = str.charCodeAt(n);
        }
        return resolve(
          (window.URL || window.webkitURL).createObjectURL(
            new Blob([array], { type: type })
          )
        );
      }
      var extName = base64.match(/data\:\S+\/(\S+);/);
      if (extName) {
        extName = extName[1];
      } else {
        reject(new Error('base64 error'));
      }
      var fileName = Date.now() + '.' + extName;
      if (typeof plus === 'object') {
        var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now());
        bitmap.loadBase64Data(
          base64,
          function () {
            var filePath = '_doc/uniapp_temp/' + fileName;
            bitmap.save(
              filePath,
              {},
              function () {
                bitmap.clear();
                resolve(filePath);
              },
              function (error) {
                bitmap.clear();
                reject(error);
              }
            );
          },
          function (error) {
            bitmap.clear();
            reject(error);
          }
        );
        return;
      }
      if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
        var filePath = wx.env.USER_DATA_PATH + '/' + fileName;
        wx.getFileSystemManager().writeFile({
          filePath: filePath,
          data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
          encoding: 'base64',
          success: function () {
            resolve(filePath);
          },
          fail: function (error) {
            reject(error);
          },
        });
        return;
      }
      reject(new Error('not support'));
    });
  },
};
